<?

class newsletter {
    
    var $send_grid_user = 'amigomedia';
    var $send_grid_key = 'am1g0pa$$';
    var $send_grid_list = 'LateDeals.ie';


// FUNCTION // add email address
function insert_email($params){

	/*$params = in($params);
	
	
	$sql = "INSERT INTO email_mailing_list
	SET email = '".$params['email']."',
	reg_date = '".mktime()."',
	user_ip = '".$params['user_ip']."'
	ON DUPLICATE KEY
	UPDATE
	reg_date = '".mktime()."',
	user_ip = '".$params['user_ip']."' ";
	

	$result = mysql_query($sql) or die (mysql_error());
	
	return mysql_insert_id();*/
    
    
    // Juan Edit - 10.09.2012
    $this->send_grid_subscribe($params);


}






// FUNCTION // Delete email address
function delete_email($params){

/*
	$params = in($params);
	
	$sql = "DELETE FROM email_mailing_list
	WHERE email = '".$params['email']."'
	LIMIT 1 ";
	
	$result = mysql_query($sql) or die (mysql_error());
        */
        
    // Juan Edit - 10.09.2012
    $this->send_grid_unsubscribe($params['email']);

}



// FUNCTION // Check if email exists
function email_exists($params){

	/*$params = in($params);

	$sql = "SELECT * FROM email_mailing_list
	WHERE email = '".$params['email']."' ";
	
	$result = mysql_query($sql) or die (mysql_error());
	
	return mysql_num_rows($result);*/
    
    // Juan Edit - 10.09.2012
    $response = json_decode($this->send_grid_get($params));

    if($response){
        return true;
    }else{
        return false;
    }
        
        

}






// FUNCTION // validate insert form
function validate_form($form_data){
	
	$my_array = array();
	
	if(!$form_data['email']){
		array_push($my_array, 'Please enter your email address.');
	}elseif(!validate_email($form_data['email'])){
		array_push($my_array, 'Please enter a valid email address.');
	}elseif($this->email_exists($form_data)){
		array_push($my_array, 'The address "'.$form_data['email'].'" is already subscribed to our database.');
	}
	
	return $my_array;
	
}





// FUNCTION // validate unsubscribe form
function validate_form_unsub($form_data){
	
	$my_array = array();
	
	if(!$form_data['email']){
		array_push($my_array, 'Please enter your email address.');
	}elseif(!validate_email($form_data['email'])){
		array_push($my_array, 'Please enter a valid email address.');
	}/*elseif(!$this->email_exists($form_data)){
		array_push($my_array, 'The address "'.$form_data['email'].'" is not subscribed to our database.');
	}*/
	
	return $my_array;
	
}


// FUNCTION // bulk add email address
function insert_bulk_email($email_array){

	$i = 0;
	foreach($email_array as $email) {
		if(!$this->email_exists(array('email'=>$email))){
			if(validate_email($email)){
				$this->insert_email(array('email'=>$email));
				$i++;			
			}
		}
	}
	return $i;

}


// FUNCTION // remove bulk email addresses
function remove_bulk_email($email_array){

	$i = 0;
	foreach($email_array as $email) {
		if(validate_email($email)){
			if($this->email_exists(array('email'=>$email))){
				$this->delete_email(array('email'=>$email));
				$i++;			
			}
		}
	}
	return $i;

}


function validate_text_file_for_parsing($file){
	
	$my_array = array();
	
	if(!$file['size']){
		array_push($my_array, 'Please upload a file');
	}else{
	
		if($file['type']!=='text/plain') array_push($my_array, 'Only upload plain text files');
		$num_lines = count_lines_in_text_file($file['tmp_name']);
		if($num_lines<1) array_push($my_array, 'This file is empty'); 
	
	}


	return $my_array;
	
}	




// FUNCTION // Get all newsletters users
function get_all(){


	$sql = "SELECT email
	FROM email_mailing_list
	GROUP BY email
	ORDER BY email ";
	
	return apply_query($sql);


}



function email_text_file_2array($file_location){


	$emails_array = array();
	if($handle = @fopen($file_location, 'r')) {
	  while (!feof($handle)) {
		  $emails_array[] = fgets($handle,9999);
	  }
	  fclose($handle);
	}
	
	return $emails_array;

}










function send_grid_post($params){

    $data = $params['data'];
    $request_url = $params['request'];

    // Generate curl request
    $session = curl_init($request_url);

    // HTTPS fix 
    curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);

    // Tell curl to use HTTP POST
    curl_setopt ($session, CURLOPT_POST, true);
    // Tell curl that this is the body of the POST
    curl_setopt ($session, CURLOPT_POSTFIELDS, $data);
    // Tell curl not to return headers, but do return the response
    curl_setopt($session, CURLOPT_HEADER, false);
    curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

    // obtain response
    $response = curl_exec($session);
    curl_close($session);
    
    return $response;

}




function send_grid_get($params){
    
    /**
     * Get all or a single email address. 
     */
    
    $sg_params = array(
        'api_user' => $this->send_grid_user,
        'api_key' => $this->send_grid_key,
        'list' => $this->send_grid_list
    );
    
    if($params['email']) $sg_params['email'] = $params['email']; // Optional
    
    $post_params = array(
      'data' => $sg_params,
      'request' => 'https://sendgrid.com/api/newsletter/lists/email/get.json' 
    );
    
    return $this->send_grid_post($post_params);
    
}



function send_grid_subscribe($params){
    
    $subscriber = json_encode(
            array(
                'email'=>$params['email'], 
                'name'=>$params['name'], 
                'user_ip'=>$params['user_ip'], 
                'reg_date' => time() 
            )
        );

    $params = array(
        'api_user' => $this->send_grid_user,
        'api_key' => $this->send_grid_key,
        'list' => $this->send_grid_list,
        'data' => $subscriber
    );
    
    $post_params = array(
      'data' => $params,
      'request' => 'https://sendgrid.com/api/newsletter/lists/email/add.json' 
    );
    
    return $this->send_grid_post($post_params);
    
}


function send_grid_unsubscribe($email){
    
    $params = array(
        'api_user' => $this->send_grid_user,
        'api_key' => $this->send_grid_key,
        'email' => $email
    );
    
    $post_params = array(
      'data' => $params,
      'request' => 'https://sendgrid.com/api/unsubscribes.add.json' 
    );
    
    return $this->send_grid_post($post_params);
    
}


function save_sendgrid_list($zip_file=false){
    
    if (!extension_loaded('zip')){

        return false;
        
    }else{

        $sg_response = json_decode($this->send_grid_get($params), TRUE);

        $csv_file = 'file.csv';

        if(is_array($sg_response)){ 

            $fp = fopen($csv_file, 'w');

            foreach ($sg_response as $row) {
                fputcsv($fp, $row);
            }

            fclose($fp);

        }

        $zip = new ZipArchive();

        if(!$zip_file) $zip_file = 'file.zip';

        if ($zip->open($zip_file, ZIPARCHIVE::CREATE) !== TRUE) {
            $response = false;
        }else{
            $zip->addFile($csv_file);
            $zip->close();
            $response = true;
        }

        unlink($csv_file); 

        return $response;

    }

}


}
?>